#pragma once
#include<pthread.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<unistd.h>
#include<netinet/in.h>
#include<string>
#include<fstream>

#define HTTP_VERSION "HTTP/1.0"
#define PATH_NAME "./wwwroot/index.html"
class TcpServer
{
private:
    int _listen_sock;
    size_t _port;
public:
    TcpServer(size_t port)
        :_port(port)
        ,_listen_sock(-1)
    {}
    void InitServer()
    {
        _listen_sock=socket(AF_INET,SOCK_STREAM,0);
        if(_listen_sock==-1)
        {
            exit(2);
        }
        sockaddr_in addr;
        addr.sin_family=AF_INET;
        addr.sin_port=htons(_port);
        addr.sin_addr.s_addr=INADDR_ANY;
        int bi=bind(_listen_sock,(sockaddr*)&addr,sizeof(addr));
        if(bi==-1)
        {
          exit(3);
        }
        if(listen(_listen_sock,5)==-1)
        {
          exit(4);
        }
    }
    static void* Routine(void* arg)
    {
        pthread_detach(pthread_self());
        int sock=*(int*)arg;
        delete (int*)arg;
        // To do
        
        char buffer[4096];
        ssize_t s=recv(sock,buffer,sizeof(buffer),0);
        /*cout<<"#####################################"<<" begin"<<endl;
        if(s>0)
        {
            cout<<buffer<<endl;
        }
        cout<<"#####################################"<<" end"<<endl;
        */
        /*std::string body="<html><head><meta charset=\"UTF-8\"></head><body><h1>hello world</h1><p>张炟快回来，干饭了,龙茂源是帅哥</p></body></html>";
        std::string response;
        response+=HTTP_VERSION;
        response+=" 200 Ok\n";
        response+="Content-Type: text/html\n";
        response+=("Content-Length: " + std::to_string(body.size()) + "\n");
        
        response+="\n";  //空行 与正文和包头分离
        
        response+=body;
        */
        std::string body;
        std::ifstream ifs(PATH_NAME);
        //ifs>>body;              //>>是以空格和换行为单位的，这里不行
        std::string line;
        while(getline(ifs,line))
        {
            body+=line;
        }
        ifs.close();
        std::string response;
        response+=HTTP_VERSION;

        response+=" 200 OK\n";
        response+="Content-Type: text/html\n";
        response+=("Content-Length: " + std::to_string(body.size()) + "\n");
        
        response+="\n";  //空行 与正文和包头分离
        response+=body;
        
        send(sock,response.c_str(),response.size(),0);
        close(sock);
        return nullptr;
    }
    void Loop()
    {
      while(1)
      {
        sockaddr_in per;
        socklen_t len=sizeof(per);
        int socket=accept(_listen_sock,(sockaddr*)&per,&len);
        if(socket!=-1)
        {
          pthread_t pid;
          int* so=new int(socket);
          pthread_create(&pid,nullptr,Routine,so);
        }
        else{
          continue;
        }
      }
    }
    ~TcpServer()
    {
        if(_listen_sock!=-1)
        {
            close(_listen_sock);
        }
    }
};
